package com.google.code.stalkernet.example.ui.action;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.AbstractAction;
import javax.swing.JOptionPane;

import com.google.code.stalkernet.example.ui.util.SocketAddressUtils;
import com.google.code.stalkernet.reactor.Reactor;
import com.google.code.stalkernet.server.Server;

/**
 * Action that adds user-provided {@link SocketAddress} to a {@link Server}.
 *
 * @author Mikhail Vladimirov
 */
public class AddServerSocketAddressAction extends AbstractAction
{
    private final static Logger logger = Logger.getLogger (
        AddServerSocketAddressAction.class.getName ());

    private final Server server;
    private final Reactor reactor;

    /**
     * Create new add server socket address action that adds user-provided
     * {@link SocketAddress} to given {@link Server}.
     *
     * @param server {@link Server} to add user-provided {@link SocketAddress}
     * to.
     */
    public AddServerSocketAddressAction (Server server, Reactor reactor)
    {
        super ("Add Server Socket Address");

        if (server == null)
            throw new IllegalArgumentException ("Server is null");

        if (reactor == null)
            throw new IllegalArgumentException ("Reactor is null");

        this.server = server;
        this.reactor = reactor;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void actionPerformed (ActionEvent e)
    {
        String socketAddressString = JOptionPane.showInputDialog(
            (Component)e.getSource (), "Server socket address:",
            "Add Server Socket Address", JOptionPane.PLAIN_MESSAGE);

        if (socketAddressString != null)
        {
            try
            {
                final SocketAddress socketAddress =
                    SocketAddressUtils.parseSocketAddress (
                        socketAddressString);

                reactor.invoke (
                    new Runnable ()
                    {
                        @Override
                        public void run ()
                        {
                            server.addSocketAddress (socketAddress);
                        }
                    });
            }
            catch (UnknownHostException ex)
            {
                logger.log (
                    Level.SEVERE,
                    "Host not found: " + socketAddressString,
                    ex);
            }
            catch (IllegalArgumentException ex)
            {
                logger.log (
                    Level.SEVERE,
                    "Invalid socket address: " + socketAddressString,
                    ex);
            }
        }
    }
}
